package love.yuanmengrobot.guoyitang.controller;
/*
 *   @Studio:CHJY · 源梦科技
 *   @Author:CHJY创幻
 *   @Ide:IntelliJ IDEA
 *   @Creation time:2021/8/11 17:20
 */


import lombok.extern.slf4j.Slf4j;
import love.yuanmengrobot.guoyitang.entity.User;
import love.yuanmengrobot.guoyitang.exception.APIException;
import love.yuanmengrobot.guoyitang.service.UserService;
import love.yuanmengrobot.guoyitang.utils.DataGridView;
import love.yuanmengrobot.guoyitang.utils.ResultEnum;
import love.yuanmengrobot.guoyitang.utils.ResultObj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
@Slf4j
@RestController
@CrossOrigin
public class LoginController {

    @Value("${wechat.appId}")
    String appId;
//
    @Value("${wechat.secret}")
    String secret;

    @Autowired
    private UserService userservice;

    /**
     * 微信授权
     * @param code
     * @return
     */
    @GetMapping("login/wxlogin")
    public String wxLogin(@RequestParam("code") String code){
        System.out.println("code"+code);

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
        url = String.format(url, appId, secret, code);
        System.out.println("url"+url);
        StringBuffer resultBuffer = null;
        try {
            URL localURL = new URL(url);
            URLConnection connection = localURL.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection)connection;

            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

            InputStream inputStream = null;
            InputStreamReader inputStreamReader = null;
            BufferedReader reader = null;
            String tempLine = null;

            resultBuffer = new StringBuffer();
            //响应失败
            if (httpURLConnection.getResponseCode() >= 300) {
                log.error("\n\n>>>>>> 微信授权请求失败, Response code is " + httpURLConnection.getResponseCode());
                throw new APIException(ResultEnum.ERROR);
            }
            try {
                inputStream = httpURLConnection.getInputStream();
                inputStreamReader = new InputStreamReader(inputStream);
                reader = new BufferedReader(inputStreamReader);

                while ((tempLine = reader.readLine()) != null) {
                    resultBuffer.append(tempLine);
                }

            } finally {
                if (reader != null) {
                    reader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            }
        } catch (Exception e) {
            throw new APIException(ResultEnum.ERROR);
        }
        log.info("\n\n >>>>>> 微信授权结果：{}", resultBuffer.toString() + "\n");
        return resultBuffer.toString();
    }

    /**
     * 登录
     * @param user
     * @return
     */
    @GetMapping("login/user")
    public DataGridView login(User user) {
        log.info("登录用户WxOpenid: "+user.getWxOpenid());
        if(user.getWxOpenid()==null||user.getWxOpenid().length()<=0) new DataGridView(-2,null);//前端输入有误！返回-2
        User user_result = this.userservice.findUserBywxOpenId(user);
        if (user_result == null) {
            new DataGridView(-1,null);//找不到数据，返回-1,null
        }
        System.out.println("#"+user_result);
        // 为了保持数据格式统一，必须使用Response包装一下
        return new DataGridView(200,user_result);//找到数据，返回200表示成功
    }













}
